package buscador.implementation;

import java.io.File;
import java.util.LinkedList;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {

	public Searcher(){
		
	}
	
	public void search(String text){	
		searchConcerts(text);
		searchRestaurants(text);
	}
	
	public void searchConcerts(String text){
		try{
			IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(System.getProperty("user.dir")+File.separator+"conciertos_index")));
			IndexSearcher searcher = new IndexSearcher(reader);
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);
			
			QueryParser parser = new QueryParser(Version.LUCENE_44, "descripcion_corta", analyzer);
			
			Query query = parser.parse(text+"*");
			
			TopDocs results = searcher.search(query, 100);
			ScoreDoc[] hits = results.scoreDocs;  
			if(hits.length == 0){
				System.out.println("Nothing");
			}
			for(int i=0; i<hits.length; i++){
				Document doc = searcher.doc(hits[i].doc);
				System.out.println(doc.get("nombre")+"-"+doc.get("descripcion_corta"));
			}
		}catch(Exception o){
			o.printStackTrace();
		}
	}
	
	public void searchRestaurants(String text){
		try{
			IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(System.getProperty("user.dir")+File.separator+"restaurantes_index")));
			IndexSearcher searcher = new IndexSearcher(reader);
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);
			
			QueryParser parser = new QueryParser(Version.LUCENE_44, "descripcion_corta", analyzer);
			
			Query query = parser.parse(text+"*");
			
			TopDocs results = searcher.search(query, 100);
			ScoreDoc[] hits = results.scoreDocs;  
			if(hits.length == 0){
				System.out.println("Nothing");
			}
			for(int i=0; i<hits.length; i++){
				Document doc = searcher.doc(hits[i].doc);
				System.out.println(doc.get("nombre")+"-"+doc.get("descripcion_corta"));
			}
		}catch(Exception o){
			o.printStackTrace();
		}
	}
}
